#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
数据可视化引擎基本使用示例

演示如何使用数据可视化引擎将自然语言问题转换为图表配置
"""

import pandas as pd
from data_engine.core.engine import DataEngine
from data_engine.utils.llm_adapter import LLMAdapter


def basic_usage_example():
    """基本使用示例"""
    print("=== 数据可视化引擎基本使用示例 ===\n")
    
    # 1. 初始化引擎
    print("1. 初始化引擎...")
    llm_client = LLMAdapter(model="gpt-3.5-turbo", api_key="your-api-key")
    engine = DataEngine(llm_client)
    print("引擎初始化完成\n")
    
    # 2. 加载销售数据集
    print("2. 加载销售数据集...")
    sales_data = pd.read_csv("test_data/sales_data.csv")
    field_descriptions = {
        "month": "月份",
        "sales": "销售金额（元）", 
        "department": "部门",
        "region": "地区"
    }
    
    engine.load_dataset(
        df=sales_data,
        dataset_desc="公司销售数据",
        table_desc="记录各部门各地区每月销售金额",
        field_desc=field_descriptions
    )
    print(f"数据集加载完成，数据形状: {sales_data.shape}\n")
    
    # 3. 处理各种类型的问题
    questions = [
        "显示每个月的销售额变化趋势",
        "比较各个部门的总销售额", 
        "各地区销售额占比情况",
        "销售额最高的前5个月份"
    ]
    
    for i, question in enumerate(questions, 1):
        print(f"问题 {i}: {question}")
        try:
            result = engine.process_query(question)
            
            if result.get("success"):
                print(f"  ✅ 生成成功")
                print(f"  📊 图表类型: {result.get('chart_type')}")
                print(f"  📄 输出类型: {result.get('type')}")
                print(f"  ⏱️ 处理时间: {result.get('processing_time', 0):.2f}秒")
                
                # 显示配置概要
                option = result.get("option", {})
                if result.get("type") == "echarts":
                    print(f"  🎯 ECharts配置包含: {list(option.keys())}")
                elif result.get("type") == "table":
                    columns = option.get("columns", [])
                    data = option.get("data", [])
                    print(f"  📋 表格: {len(columns)}列, {len(data)}行数据")
            else:
                print(f"  ❌ 生成失败: {result.get('error')}")
                
        except Exception as e:
            print(f"  ❌ 异常: {str(e)}")
        print()
    
    # 4. 获取数据样本
    print("4. 数据样本预览...")
    sample_data = engine.get_sample_data(max_rows=3)
    print(sample_data)
    print()


def employee_analysis_example():
    """员工绩效分析示例"""
    print("=== 员工绩效分析示例 ===\n")
    
    # 初始化引擎
    llm_client = LLMAdapter(model="gpt-3.5-turbo")
    engine = DataEngine(llm_client)
    
    # 加载员工数据
    employee_data = pd.read_csv("test_data/employee_data.csv")
    engine.load_dataset(
        df=employee_data,
        dataset_desc="员工绩效数据", 
        table_desc="记录员工基本信息和绩效数据",
        field_desc={
            "employee_id": "员工编号",
            "name": "姓名",
            "department": "部门", 
            "position": "职位",
            "performance_score": "绩效分数",
            "salary": "薪资",
            "work_years": "工作年限",
            "age": "年龄"
        }
    )
    
    # 分析问题
    questions = [
        "员工薪资和绩效分数之间的关系",
        "各部门平均绩效分数对比",
        "绩效分数最高的前10名员工",
        "工作年限与薪资的关系"
    ]
    
    for question in questions:
        print(f"问题: {question}")
        try:
            result = engine.process_query(question)
            if result.get("success"):
                print(f"  ✅ 图表类型: {result.get('chart_type')}")
                print(f"  📊 输出类型: {result.get('type')}")
            else:
                print(f"  ❌ 失败: {result.get('error')}")
        except Exception as e:
            print(f"  ❌ 异常: {str(e)}")
        print()


def multi_dataset_example():
    """多数据集示例"""
    print("=== 多数据集支持示例 ===\n")
    
    # 初始化引擎
    llm_client = LLMAdapter(model="gpt-3.5-turbo")
    engine = DataEngine(llm_client)
    
    # 加载销售数据
    sales_data = pd.read_csv("test_data/sales_data.csv")
    engine.load_dataset(
        df=sales_data,
        dataset_desc="销售数据",
        table_desc="各部门销售金额记录",
        field_desc={
            "month": "月份",
            "sales": "销售金额（元）",
            "department": "部门",
            "region": "地区"
        }
    )
    
    # 加载员工数据
    employee_data = pd.read_csv("test_data/employee_data.csv")
    engine.load_dataset(
        df=employee_data,
        dataset_desc="员工数据",
        table_desc="员工基本信息和绩效",
        field_desc={
            "name": "姓名",
            "department": "部门",
            "performance_score": "绩效分数",
            "salary": "薪资"
        }
    )
    
    print("已加载销售数据和员工数据")
    
    # 跨数据集分析
    questions = [
        "结合销售数据和员工数据，分析各部门的业绩表现",
        "哪个部门的销售额最高，该部门员工的平均绩效如何？"
    ]
    
    for question in questions:
        print(f"问题: {question}")
        try:
            result = engine.process_query(question)
            if result.get("success"):
                print(f"  ✅ 分析完成: {result.get('chart_type')}")
            else:
                print(f"  ❌ 失败: {result.get('error')}")
        except Exception as e:
            print(f"  ❌ 异常: {str(e)}")
        print()


def custom_llm_example():
    """自定义LLM模型示例"""
    print("=== 自定义LLM模型示例 ===\n")
    
    # 使用Claude模型
    try:
        claude_client = LLMAdapter(
            model="claude-3-sonnet-20240229",
            api_key="your-claude-api-key",
            base_url="https://api.anthropic.com"
        )
        engine_claude = DataEngine(claude_client)
        print("✅ Claude模型初始化成功")
    except Exception as e:
        print(f"❌ Claude模型初始化失败: {e}")
    
    # 使用国产模型
    try:
        qwen_client = LLMAdapter(
            model="qwen-plus",
            api_key="your-qwen-api-key"
        )
        engine_qwen = DataEngine(qwen_client)
        print("✅ 通义千问模型初始化成功")
    except Exception as e:
        print(f"❌ 通义千问模型初始化失败: {e}")
    
    print()


def missing_description_example():
    """缺失描述信息处理示例"""
    print("=== 缺失描述信息处理示例 ===\n")
    
    # 初始化引擎
    llm_client = LLMAdapter(model="gpt-3.5-turbo")
    engine = DataEngine(llm_client)
    
    # 加载测试数据
    sales_data = pd.read_csv("test_data/sales_data.csv")
    
    # 场景1: 完全没有描述信息
    print("场景1: 完全没有描述信息")
    engine.load_dataset(
        df=sales_data,
        dataset_desc=None,  # 数据集描述缺失
        table_desc=None,    # 表格描述缺失
        field_desc=None     # 字段描述缺失
    )
    
    result = engine.process_query("显示销售额趋势")
    if result.get("success"):
        print(f"  ✅ 成功生成图表: {result.get('chart_type')}")
    else:
        print(f"  ❌ 失败: {result.get('error')}")
    print()
    
    # 场景2: 部分描述信息
    print("场景2: 部分描述信息")
    engine.load_dataset(
        df=sales_data,
        dataset_desc="销售数据",
        table_desc=None,    # 表格描述缺失
        field_desc={        # 部分字段描述
            "sales": "销售金额"
            # 其他字段描述缺失
        }
    )
    
    result = engine.process_query("各部门销售额对比")
    if result.get("success"):
        print(f"  ✅ 成功生成图表: {result.get('chart_type')}")
    else:
        print(f"  ❌ 失败: {result.get('error')}")
    print()
    
    # 场景3: 空字符串描述
    print("场景3: 空字符串描述")
    engine.load_dataset(
        df=sales_data,
        dataset_desc="",    # 空字符串会被处理为None
        table_desc="",
        field_desc={}       # 空字典会被处理为None
    )
    
    result = engine.process_query("销售额分布情况")
    if result.get("success"):
        print(f"  ✅ 成功生成图表: {result.get('chart_type')}")
    else:
        print(f"  ❌ 失败: {result.get('error')}")
    print()
    
    print("引擎自动处理策略:")
    print("  1. 使用数据字段名和数据类型信息补充缺失的字段描述")
    print("  2. 在提示词中添加'请根据数据字段和样本数据理解数据含义'的指导")
    print("  3. 智能组装提示词，避免冗余信息")
    print()


def safe_execution_example():
    """安全执行配置示例"""
    print("=== 安全执行配置示例 ===\n")
    
    # 配置安全参数
    llm_client = LLMAdapter(model="gpt-3.5-turbo")
    engine = DataEngine(
        llm_client=llm_client,
        execution_timeout=30,  # 代码执行超时时间
        max_memory_mb=100,     # 最大内存使用
        allowed_modules=['pandas', 'numpy']  # 允许的模块
    )
    
    print("✅ 安全执行环境配置完成")
    print("  - 执行超时: 30秒")
    print("  - 内存限制: 100MB")
    print("  - 允许模块: pandas, numpy")
    print()


if __name__ == "__main__":
    """运行所有示例"""
    try:
        # 基本使用示例
        basic_usage_example()
        
        # 员工分析示例
        employee_analysis_example()
        
        # 多数据集示例  
        multi_dataset_example()
        
        # 缺失描述信息处理示例
        missing_description_example()
        
        # 自定义LLM示例
        custom_llm_example()
        
        # 安全配置示例
        safe_execution_example()
        
        print("🎉 所有示例运行完成！")
        
    except Exception as e:
        print(f"❌ 示例运行失败: {e}")
        print("请确保：")
        print("1. 已安装所有依赖: pip install -r requirements.txt")
        print("2. 测试数据文件存在于 test_data/ 目录")
        print("3. 已配置相应的LLM API密钥")